package com.cictec.middleware.distribute.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.cictec.middleware.CloudConstants;
import com.cictec.middleware.commons.utils.PMSUtils;
import com.cictec.middleware.core.entity.Device;

@Service
public class RedisService {

	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	
	
	public Device getDeviceBySerialNumber(String serialNumber) {
		Device device = null;
		List<Device> list = getDeviceList();
		for (Device device2 : list) {
			if(PMSUtils.isNull(device2.getDevRefId()).equals(serialNumber)){
				device = device2;
				break;
			}
		}
		return device;
	}
	
	public List<Device> getDeviceList(){
		List<Device> list = new ArrayList<Device>();
		if(stringRedisTemplate.hasKey(CloudConstants.REDIS_CLOUD_DEVICE)){
			HashOperations<String, String, String> ops = stringRedisTemplate.opsForHash();
			List<String> rlist = ops.values(CloudConstants.REDIS_CLOUD_DEVICE);
			for (String device : rlist) {
				list.add(JSON.parseObject(device, Device.class));
			}
		}
		return list;
	}
	
	public Device getDeviceByDevCode(String devCode){
		Device device = null;
		if(stringRedisTemplate.hasKey(CloudConstants.REDIS_CLOUD_DEVICE)){
			HashOperations<String, String, String> ops = stringRedisTemplate.opsForHash();
			if(ops.hasKey(CloudConstants.REDIS_CLOUD_DEVICE, devCode)){
				String json = ops.get(CloudConstants.REDIS_CLOUD_DEVICE, devCode);
				device = JSON.parseObject(json, Device.class);
			}
		}
		return device;
	}
}
